/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package portal.userManager;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import portal.mailservice.Emailer;

/**
 *
 * @author Riso-Desktop
 */
@WebServlet(name = "user_panel", urlPatterns = {"/user_panel.jsp"})
public class user_panel extends HttpServlet {
    String driver = portal.constants.Database.DATABASE_DRIVER;
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;
    String userName = portal.constants.Database.DATABASE_USER;
    String password = portal.constants.Database.DATABASE_PASSWORD;
    String URL = portal.constants.Database.DATABASE_URL;
    HttpSession session;
    PrintWriter out;

    @Override
    public void init() {
        try {
            super.init();
            Class.forName(driver);
            con = DriverManager.getConnection(URL, userName, password);
        } catch (Exception ex) {
        }
    }

    public int prihlasenie(String user, String heslo) {
        int id = 0;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] nezakodovaneHeslo = heslo.getBytes("UTF-8");
            byte[] zakodovaneHeslo = md.digest(nezakodovaneHeslo);
            stmt = con.createStatement();
            rs = stmt.executeQuery("select max(id_usera) as iid,count(id_usera) as pocet from user where meno='"+
                    user+"' and heslo='"+new String(zakodovaneHeslo) +"'");
            rs.next();
            if(rs.getInt("pocet")==1){
                id = rs.getInt("iid");
                stmt.executeUpdate("update user set pocet_navstev = (pocet_navstev + 1) , posledne_prihlasenie = '"+new Timestamp(System.currentTimeMillis())+"' where id_usera = "+id+"");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return id;
    }

    
    private void GetUserSettings(int ID_usera){
        try {
        
         stmt = con.createStatement();
         rs = stmt.executeQuery("select * from user_nastavenia where id_usera = "+ID_usera);
         rs.next();
         session.setAttribute("pocet_poloziek", rs.getInt("pocet_poloziek_na_stranu"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    

    private void vypisBody() {
        out.println("<div class=\"panel\" style=\"width: 160px;\">");
        if (session.getAttribute("meno_usera") != null && (Integer) session.getAttribute("id_usera") > 0) {
            out.println("Prihlásený ako: " + session.getAttribute("meno_usera")
                    + "            <br/>\n"
                    + "            <a href=\"Odhlasenie\" >Odhlásiť sa</a>");
        } else {
            out.println("<form action=\"Login\" method=\"post\" >\n"
                    + "                <input name=\"meno\" value=\"\" type=\"text\" size=\"10\" placeholder=\"Vaša e-mailová adresa\">\n"
                    + "                <br/>\n"
                    + "                <input name=\"heslo\" type=\"password\" size=\"10\" placeholder=\"Vaše heslo\">\n"
                    + "                <br/>\n"
                    + "                <input type=\"submit\" value=\"Prihlásiť\" name=\"submit\" class=\"submit\">\n"
                    + "            </form>\n"
                    + "            <a href=\"registracia.jsp\" >Ešte nemám účet</a><br/>\n"
                    + "            <a class=\"obnovahesla\" href=\"obnovahesla.jsp\" target=\"iframe_hlavny\" >Zabudol som heslo</a>");
        }
        out.println("</div>");
    }

    

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        out = response.getWriter();
        session = request.getSession();
        try {
            if(request.getParameter("submit")!=null&&request.getParameter("submit").equals("Prihlásiť")){
            int id = prihlasenie(request.getParameter("meno"), request.getParameter("heslo"));
            if(id>0){
            session = request.getSession();
            session.setMaxInactiveInterval(900);
            session.setAttribute("id_usera", id);
            session.setAttribute("meno_usera", request.getParameter("meno"));
            GetUserSettings(id);
            }
            }
            vypisBody();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
